<template>
  <a-menu
    theme="dark"
    mode="inline"
    :selectedKeys="selectedKeys"
    @click="menuClick"
  >
    <template v-for="(menu, index) in menuTree">
      <a-menu-item
        v-if="!menu.children || menu.children.length == 0"
        :key="menu.key"
      >
        <a-icon v-if="menu.icon" :type="menu.icon" />
        <span>{{ menu.name }}</span>
      </a-menu-item>
      <custom-sub-menu v-else :subMenu="menu" :key="index"></custom-sub-menu>
    </template>
  </a-menu>
</template>

<script>
import MenuItem from "./MenuItem.vue";
import { getMenuTree } from "@/api/MenuApi";
import { getSelectedKeys } from "@/utils/ComUtils";
export default {
  data() {
    return {
      selectedKeys: [],
      menuTree: [],
    };
  },
  computed: {
    routePath() {
      return this.$route.path;
    },
  },
  watch: {
    routePath: {
      handler() {
        this.refreshSelectKeys();
      },
    },
  },
  mounted() {
    getMenuTree()
      .then((resp) => {
        this.menuTree = resp.data;
        this.refreshSelectKeys();
      })
      .catch(() => {});
  },
  methods: {
    refreshSelectKeys() {
      // 激活选中的菜单 - 高亮
      this.selectedKeys = getSelectedKeys(this.routePath);
    },
    menuClick(menu) {
      let keyPath = menu.keyPath;
      if (!keyPath || keyPath.length == 0) {
        console.warn("keyPath = " + keyPath);
        return;
      }
      let routePath = "";
      keyPath.reverse().forEach((item) => {
        routePath += item;
      });
      this.$router.push({ path: routePath });
    },
  },
  components: {
    "custom-sub-menu": MenuItem,
  },
};
</script>
<style>
</style>